package com.yuandengta.yomall.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yuandengta.common.constant.OrderConstant;
import com.yuandengta.common.to.SkuHasStockTO;
import com.yuandengta.common.to.mq.OrderTO;
import com.yuandengta.common.to.mq.SeckillOrderTO;
import com.yuandengta.common.utils.R;
import com.yuandengta.common.vo.MemberVO;
import com.yuandengta.yomall.order.constant.OrderCheckEnum;
import com.yuandengta.yomall.order.constant.OrderDelStatusEnum;
import com.yuandengta.yomall.order.constant.OrderStatusEnum;
import com.yuandengta.yomall.order.constant.RabbitConstant;
import com.yuandengta.yomall.order.entity.OrderItemEntity;
import com.yuandengta.yomall.order.exception.OrderException;
import com.yuandengta.yomall.order.feign.CartFeignService;
import com.yuandengta.yomall.order.feign.MemberFeignService;
import com.yuandengta.yomall.order.feign.ProductFeignService;
import com.yuandengta.yomall.order.feign.WareFeignService;
import com.yuandengta.yomall.order.interceptor.LoginInterceptor;
import com.yuandengta.yomall.order.service.OrderItemService;
import com.yuandengta.yomall.order.to.OrderCreateTO;
import com.yuandengta.yomall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;

import com.yuandengta.yomall.order.dao.OrderDao;
import com.yuandengta.yomall.order.entity.OrderEntity;
import com.yuandengta.yomall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVO> submitVOThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 返回订单确认页需要的数据
     * @return
     * @throws Exception
     */
    @Override
    public OrderConfirmVO confirmOrder() throws Exception {
        OrderConfirmVO confirmVO = new OrderConfirmVO();
        MemberVO memberVO = LoginInterceptor.threadLocal.get();

        // 获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            // 每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询会员的所有收货地址
            List<MemberAddressVO> address = memberFeignService.getAddress(memberVO.getId());
            confirmVO.setAddress(address);
        }, executor);

        CompletableFuture<Void> getItemsFuture = CompletableFuture.runAsync(() -> {
            // 每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询会员的所有购物项
            // feign在远程调用之前要构造请求，调用很多拦截器（RequestInterceptor...）
            List<OrderItemVO> items = cartFeignService.getCartItems();
            confirmVO.setItems(items);
        }, executor).thenRunAsync(() -> {
            List<Long> skuIds = confirmVO.getItems().stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            // 远程查询商品库存
            List<SkuHasStockTO> skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            if (skuHasStock != null) {
                Map<Long, Boolean> map = skuHasStock.stream()
                        .collect(Collectors.toMap(SkuHasStockTO::getSkuId, SkuHasStockTO::getHasStock));
                confirmVO.setStocks(map);
            }
        }, executor);

        // 用户积分
        Integer integration = memberVO.getIntegration();
        confirmVO.setIntegration(integration);

        // 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        // token向redis放置一份
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVO.getId(), token,
                30, TimeUnit.MINUTES);
        // token向客户端放置一份
        confirmVO.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture, getItemsFuture).get();

        return confirmVO;
    }

    /**
     * 下单操作
     *  - Transactional 本地事务，在分布式系统下，只能控制自己的回滚，控制不了其他服务的回滚
     *  - GlobalTransactional Seata分布式事务来保证整个业务的回滚（高并发场景不适合）
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitResponseVO submitOrder(OrderSubmitVO vo) {
        submitVOThreadLocal.set(vo);
        OrderSubmitResponseVO response = new OrderSubmitResponseVO();
        response.setCode(OrderCheckEnum.SUCCESS.getCode());
        MemberVO memberVO = LoginInterceptor.threadLocal.get();
        // 验证令牌，令牌的对比和删除必须保证原子性
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        // 原子验证令牌和删除令牌
        Long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVO.getId()),
                orderToken);
        if (result == 0L){
            // 验证失败
            response.setCode(OrderCheckEnum.TOKEN_EXCEPTION.getCode());
            return response;
        }
        // 1. 创建订单，订单项等信息
        OrderCreateTO order = createOrder();
        // 2. 验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        if(Math.abs(payAmount.subtract(payPrice).doubleValue()) > 0.01) {
            // 验价异常
            response.setCode(OrderCheckEnum.PRICE_EXCEPTION.getCode());
            return response;
        }
        // 3.保存订单
        saveOrder(order);
        // 4. 锁定库存，只要有异常需回滚订单数据
        WareSkuLockVO lockVO = new WareSkuLockVO();
        lockVO.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVO> itemVOS = order.getOrderItems().stream().map(item -> {
            OrderItemVO itemVO = new OrderItemVO();
            itemVO.setSkuId(item.getSkuId());
            itemVO.setCount(item.getSkuQuantity());
            itemVO.setTitle(item.getSkuName());
            return itemVO;
        }).collect(Collectors.toList());
        lockVO.setLocks(itemVOS);
        // 远程锁定订单商品库存
        R r = wareFeignService.orderLockStock(lockVO);
        if (r.getCode() != 0) {
            // 锁定失败
            // 为了保证高并发，库存服务自己回滚
            // 高并发场景不适合使用 Seata AT模式
            // 库存服务本身使用自动解锁模式（柔性事务：可靠消息+最终一致性）
            response.setCode(OrderCheckEnum.STOCK_EXCEPTION.getCode());
            String msg = (String) r.get("msg");
            throw new OrderException(msg);
        }

        response.setOrder(order.getOrder());

        // 订单创建成功，发送消息
        rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EVENT_EXCHANGE,
                RabbitConstant.ORDER_DELAY_QUEUE_ROUTING_KEY, order.getOrder());

        return response;
    }

    /**
     * 查询订单
     * @param orderSn 订单号
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 关闭订单
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询当前订单的最新状态
        OrderEntity orderEntity = getById(entity.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(orderEntity.getStatus())) {
            // 关单
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            updateById(orderEntity);

            // 释放订单，发送消息
            OrderTO orderTO = new OrderTO();
            BeanUtils.copyProperties(orderEntity, orderTO);

            // 保证消息一定会成功发送出去，每一个消息做好日志记录（写入消息表）
            // 定期扫描消息表，将失败的消息再次发送
            rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EVENT_EXCHANGE,
                    RabbitConstant.ORDER_RELEASE_OTHER_ROUTING_KEY, orderTO);
        }
    }

    /**
     * 获取订单支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVO getOrderPay(String orderSn) {
        PayVO payVO = new PayVO();
        OrderEntity orderEntity = getOrderByOrderSn(orderSn);
        payVO.setOut_trade_no(orderEntity.getOrderSn());
        // 支付宝仅支持2位小数金额
        BigDecimal payAmount = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVO.setTotal_amount(payAmount.toString());
        return payVO;
    }

    /**
     * 查询当前登录会员所有订单信息
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberVO memberVO = LoginInterceptor.threadLocal.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberVO.getId()).orderByDesc("id")
        );

        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> items = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItems(items);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntities);

        return new PageUtils(page);
    }

    /**
     * 修改订单状态
     * @param outTradeNo
     * @param status
     */
    @Override
    public void updateOrderStatus(String outTradeNo, Integer status) {
        baseMapper.updateOrderStatus(outTradeNo, status);
    }

    /**
     * 创建秒杀订单
     * @param seckillOrder
     */
    @Override
    public void createSeckillOrder(SeckillOrderTO seckillOrder) {
        // 保存订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        save(orderEntity);

        // 保存订单项
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());
        orderItemEntity.setRealAmount(multiply);
        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单
     * @param order
     */
    private void saveOrder(OrderCreateTO order) {
        // 保存订单
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        save(orderEntity);
        // 保存订单项
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单
     * @return
     */
    private OrderCreateTO createOrder(){
        OrderCreateTO orderCreateTO = new OrderCreateTO();
        // 1.构建订单
        // 生成订单号，可以根据实际情况来采用业务ID生成规则（统一ID服务中心：用来提供ID策略及ID值）
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        orderCreateTO.setOrder(orderEntity);

        // 2. 获取所有订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        orderCreateTO.setOrderItems(orderItemEntities);

        // 3. 计算价格，积分相关信息
        computePrice(orderEntity, orderItemEntities);

        return orderCreateTO;
    }

    /**
     * 计算价格，积分相关信息
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal totalAmount = new BigDecimal("0.00");
        BigDecimal couponAmount = new BigDecimal("0.00");
        BigDecimal promotionAmount = new BigDecimal("0.00");
        BigDecimal integrationAmount = new BigDecimal("0.00");
        Integer growth = 0;
        Integer integration = 0;
        for (OrderItemEntity itemEntity : orderItemEntities) {
            totalAmount = totalAmount.add(itemEntity.getRealAmount());
            couponAmount = couponAmount.add(itemEntity.getCouponAmount());
            promotionAmount = promotionAmount.add(itemEntity.getPromotionAmount());
            integrationAmount = integrationAmount.add(itemEntity.getIntegrationAmount());
            growth += itemEntity.getGiftGrowth();
            integration += itemEntity.getGiftIntegration();
        }
        // 订单的总额
        orderEntity.setTotalAmount(totalAmount);
        // 应付总额 = 订单总额 + 运费
        orderEntity.setPayAmount(totalAmount.add(orderEntity.getFreightAmount()));
        // 各种折扣金额
        orderEntity.setCouponAmount(couponAmount);
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        // 成长值
        orderEntity.setGrowth(growth);
        // 积分
        orderEntity.setIntegration(integration);
    }

    /**
     * 构建订单
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberVO memberVO = LoginInterceptor.threadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        // 设置订单号
        orderEntity.setOrderSn(orderSn);
        // 设置会员信息
        orderEntity.setMemberId(memberVO.getId());
        orderEntity.setMemberUsername(memberVO.getUsername());
        // 获取收货人相关信息
        OrderSubmitVO orderSubmitVO = submitVOThreadLocal.get();
        R r = wareFeignService.getFare(orderSubmitVO.getAddrId());
        FareVO fareVO = r.getData("data", new TypeReference<FareVO>() {
        });
        orderEntity.setReceiverCity(fareVO.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareVO.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareVO.getAddress().getName());
        orderEntity.setReceiverPhone(fareVO.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareVO.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareVO.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareVO.getAddress().getRegion());
        // 设置运费
        orderEntity.setFreightAmount(fareVO.getFare());
        // 设置订单状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        // 订单自动确认时间
        orderEntity.setAutoConfirmDay(OrderConstant.ORDER_CONFIRM_DAY);
        // 订单删除状态
        orderEntity.setDeleteStatus(OrderDelStatusEnum.NOT_DELETE.getCode());

        return orderEntity;
    }

    /**
     * 构建所有订单项
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVO> cartItems = cartFeignService.getCartItems();
        if (cartItems != null && cartItems.size() > 0) {
            List<OrderItemEntity> orderItemEntities = cartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());

            return orderItemEntities;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 商品spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        if (r.getCode() == 0) {
            SpuInfoVO spuInfoVO = r.getData("data", new TypeReference<SpuInfoVO>() {
            });
            orderItemEntity.setSpuId(spuInfoVO.getId());
            orderItemEntity.setSpuBrand(spuInfoVO.getBrandId().toString());
            orderItemEntity.setSpuName(spuInfoVO.getSpuName());
            orderItemEntity.setCategoryId(spuInfoVO.getCatalogId());

            // 商品sku信息
            orderItemEntity.setSkuId(skuId);
            orderItemEntity.setSkuName(cartItem.getTitle());
            orderItemEntity.setSkuPic(cartItem.getImage());
            orderItemEntity.setSkuPrice(cartItem.getPrice());
            String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
            orderItemEntity.setSkuAttrsVals(skuAttr);
            orderItemEntity.setSkuQuantity(cartItem.getCount());
            // 成长值
            orderItemEntity.setGiftGrowth(cartItem.getPrice()
                    .multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
            // 积分
            orderItemEntity.setGiftIntegration(cartItem.getPrice()
                    .multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
            // 价格
            orderItemEntity.setPromotionAmount(new BigDecimal("0"));
            orderItemEntity.setCouponAmount(new BigDecimal("0"));
            orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
            // 订单的实际金额 = 总额 - 优惠券金额 - 促销金额 - 积分优惠金额
            BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
            BigDecimal real = origin.subtract(orderItemEntity.getCouponAmount())
                    .subtract(orderItemEntity.getPromotionAmount())
                    .subtract(orderItemEntity.getIntegrationAmount());
            orderItemEntity.setRealAmount(real);
        } else {
            log.error("调用远程服务 yomall-product 查询商品信息异常");
        }


        return orderItemEntity;
    }

}